const {exec} = require('child_process');

/**
 * 获取 git 提交记录
 * @param {number} [line] 获取的条数
 * @param {string} [filePath] 要获取的文件路径
 * @return {Promise<{
 *     commit: string,
 *     author: string,
 *     authorEmail: string,
 *     date: number,
 *     message: string,
 *     files: string[]
 * }[]>}
 */
function getGitLog(line, filePath = '') {
    const commitLineFlag = '[commit]'
    const _cmd = `git log ${line ? '-' + line : ''} --pretty=format:"${commitLineFlag}%H||%an||%ae||%at||%s"` + ' ' + (filePath || '--name-only')
    return new Promise((resolve, reject) => {
        exec(_cmd, (code, stdout, stderr) => {
            if (code) {
                reject(stderr)
            } else {
                const logList = []
                const list = stdout.split('\n')
                for (let log of list) {
                    if (log) {
                        if (log.startsWith(commitLineFlag)) {
                            const logSplit = log.substring(commitLineFlag.length).split('||')
                            const logInfo = {
                                commit: logSplit[0],
                                author: logSplit[1],
                                authorEmail: logSplit[2],
                                date: new Date(parseInt(logSplit[3]) * 1000).getTime(),
                                message: logSplit.slice(4).join('||'),
                                files: []
                            }
                            logList.push(logInfo)
                        } else {
                            if (logList[logList.length - 1]) {
                                logList[logList.length - 1].files.push(log)
                            }
                        }
                    }
                }
                resolve(logList)
            }
        })
    })
}

exports.getGitLog = getGitLog;
